<template>
  <el-dialog
    append-to-body
    :before-close="cancel"
    show-summary
    width="70%"
    :visible.sync="value"
  >
    <template slot="title">
      下级代理佣金
    </template>
    <ModalWrapper>
      <div class="header-description-view">
        <div class="header-item-view">
          <div>账户名</div>
          <span>{{tableData.username}}</span>
        </div>
        <div class="header-item-view">
          <div>月份</div>
          <span>{{tableData.month}}</span>
        </div>
        <div class="header-item-view">
          <div>有效下级代理总数（有效/总数）</div>
          <span>{{tableData.commissionRate}}</span>
        </div>
        <div class="header-item-view">
          <div>下级代理佣金总额</div>
          <span>{{tableData.amount}}</span>
        </div>
        <el-button
          type="primary"
          :loading="downloadLoading"
          :disabled="exportDisabled"
          @click="handleExportExcel"
          v-if="roleCheck(commSettleRoleType.subordExport)"
        >
          导出
        </el-button>
      </div>
      <TreeProxyTable
        :loading="loading"
        :headerMap="headerMap"
        :treeData="tableData.subList"
        :colorKeyList="['memberAmount', 'proxyAmount']"
        @loadNode="loadNode"
      />
    </ModalWrapper>
  </el-dialog>

</template>

<script>

  // utils
  import { mapToArray, formatCommMode } from '@/utils/base';

  // constants
  import { commSettleRoleType } from '@/router/commissionRoutes'

  // components
  import ModalWrapper from '@/components/ModalWrapper'
  import TreeProxyTable from './treeProxyTable'

  // build
  import { grid } from '@/build'

  // services
  import { getCommissionSubProxy, getCommissionExportSubProxy } from '@/services/api/commission'

  const headerMap = {
    level: '代理层级',
    username: '代理账户名',
    commissionRate: '直属代理数（有效 / 总数)',
    memberAmount: '下级会员佣金',
    proxyAmount: '下级代理佣金',
    mode: '模式',
  };

  export default {
    name: 'sub-commission-dialog',
    props: ['value', 'id'],
    mixins: [grid],
    components: {
      ModalWrapper,
      TreeProxyTable,
    },
    data() {
      return {
        commSettleRoleType,
        headerMap,
        tableData: {
          subList: [],
        },
      }
    },
    computed: {
      exportDisabled() {
        return !(Array.isArray(this.tableData.subList) && this.tableData.subList.length)
      },
    },
    methods: {
      cancel() {
        this.$emit('input', false)
      },
      formatData(data) {
        const { subList = [] } = data || {};
        if (!subList.length) return [];
        return subList.map(item => ({
          ...item,
          memberAmount: _.currency(item.memberAmount),
          proxyAmount: _.currency(item.proxyAmount),
          leaf: item.childSize === 0,
          children: null,
          commissionRate: `${item.effectChildSize}/${item.childSize}`,
          mode: formatCommMode(item.mode).name,
        }));
      },
      formatExcelData(oldList, newList = []) {
        if (!oldList.length) return [];
        return oldList.map(item => {
          const currObject = {
            ...item,
            username: item.name,
            memberAmount: _.currency(item.memberCommission),
            proxyAmount: _.currency(item.proxyCommission),
            commissionRate: `${item.proxyEffectNum}/${item.proxyNum}`,
            mode: formatCommMode(item.mode).name,
          };
          if (currObject.subList) {
            delete currObject.subList;
          }
          newList.push(currObject);
          if (item.subList.length) {
            return this.formatExcelData(item.subList, newList);
          }
        });
      },
      async loadNode(node, resolve) {
        if (node.level === 0) {
          return resolve(
            this.tableData.subList
          );
        }
        try {
          const [status, result] = await getCommissionSubProxy({
            settleId: this.id,
            parentId: node.data.uid,
          });
          if (!status) throw new Error(result.message);
          const data = this.formatData(result);
          resolve(data);
        } catch (e) {
          this.$message({
            message: `获取数据失败.${e.message || ''}`,
            type: 'error'
          })
        }
      },
      async handleExportExcel() {
        try {
          this.downloadLoading = true;
          const [status, result] = await getCommissionExportSubProxy({
            settleId: this.id,
          });
          if (!status) throw new Error(result.message);
          if (!result.length) throw new Error('暂无导出数据');
          const { username = '', month = '' } = this.tableData;
          const exportData = [];
          this.formatExcelData(result, exportData)
          const filename = `下级代理佣金报表.${username}.${month}.csv`;
          const header = mapToArray(headerMap);
          const filterField = Object.keys(headerMap);
          this.export2Excel(header, filterField, exportData, filename)
        } catch (e) {
          this.$message({
            message: `${e.message || ''}`,
            type: 'error'
          })
        } finally {
          this.downloadLoading = false;
        }
      },
    },
    mounted() {
      this.bindGet(getCommissionSubProxy, 'tableData', {
        sendingData: { settleId: this.id },
        format: (data) => ({
          ...data,
          amount: _.currency(data.amount),
          commissionRate: `${data.effectChildSize || 0}/${data.childSize || 0}`,
          subList: this.formatData(data),
        }),
      })
      this.getAll()
    }
  }
</script>

<style lang="scss" scoped>
  .header-description-view {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-left: 50px;

    .header-item-view {
      min-height: 60px;
      display: flex;
      flex-direction: column;
      align-items: center;

      > div {
        font-weight: 700;
      }
      > span {
        margin-top: 12px;
      }
    }
  }
</style>
